﻿using Newtonsoft.Json;
using PMIS.Common;
using PMIS.Common.Dialog;
using PMIS.Events;
using PMIS.HttpRequest;
using PMIS.Models;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using System.ComponentModel.DataAnnotations;
using System.Windows;

namespace PMIS.ViewModels
{
    public class LoginViewModel : DialogViewModelBase
    {
        private string _username;
        private string _password;
        private string _usernameError;
        private string _passwordError;
        private bool _isLogin;
        private bool _isRemberMe;

        private readonly HttpService _httpService;

        private readonly IEventAggregator _eventAggregator;

        public LoginViewModel(HttpService httpService, IEventAggregator eventAggregator)
        {
            _httpService = httpService;
            _eventAggregator = eventAggregator;

            this.Title = "登录";

            IsRemberMe = AppSettingsHelper.IsRemberMe;

            if (!string.IsNullOrWhiteSpace(AppSettingsHelper.UserName))
            {
                Username = DesEncryptHelper.Decrypt3Des(AppSettingsHelper.UserName);
            }
            if (!string.IsNullOrWhiteSpace(AppSettingsHelper.Password))
            {
                Password = DesEncryptHelper.Decrypt3Des(AppSettingsHelper.Password);
            }
        }

        [Required(ErrorMessage = "请输入用户名")]
        public string Username
        {
            get { return _username; }
            set
            {
                SetProperty(ref _username, value);
                ValidateFieldValue(nameof(Username), _username);
            }
        }

        [Required(ErrorMessage = "请输入密码")]
        public string Password
        {
            get { return _password; }
            set
            {
                SetProperty(ref _password, value);
                ValidateFieldValue(nameof(Password), _password);
            }
        }

        public string UsernameError
        {
            get => _usernameError;
            set { SetProperty(ref _usernameError, value); }
        }

        public string PasswordError
        {
            get => _passwordError;
            set { SetProperty(ref _passwordError, value); }
        }

        public bool IsLogin
        {
            get => _isLogin;
            set { SetProperty(ref _isLogin, value); }
        }

        public bool IsRemberMe
        {
            get => _isRemberMe;
            set { SetProperty(ref _isRemberMe, value); }
        }

        private DelegateCommand _loginCommand;
        public DelegateCommand LoginCommand => _loginCommand ?? new DelegateCommand(async () => { await OnLogin(); });

        private async Task OnLogin()
        {
            ValidateFieldValue(nameof(Username), Username);
            ValidateFieldValue(nameof(Password), Password);

            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
            {
                return;
            }

            IsLogin = true;

            var parameters = new LoginDto() { Username = Username, Password = Password };
            var response = await _httpService.PostAsync(Api.LOGIN, parameters);
            if (response?.code == 1)
            {
                if (response.data != null)
                {
                    var user = JsonConvert.DeserializeObject<AuthenticateUser>(JsonConvert.SerializeObject(response.data));

                    AppSettingsHelper.IsRemberMe = IsRemberMe;

                    if (IsRemberMe)
                    {
                        AppSettingsHelper.UserName = DesEncryptHelper.Encrypt3Des(Username);
                        AppSettingsHelper.Password = DesEncryptHelper.Encrypt3Des(Password);
                    }
                    else
                    {
                        AppSettingsHelper.UserName = string.Empty;
                        AppSettingsHelper.Password = string.Empty;
                    }

                    AccountInfo.Instance.UserId = user.Id;
                    AccountInfo.Instance.UserName = user.Username;
                    AccountInfo.Instance.Token = user.Token;
                    AccountInfo.Instance.RoleId = user.RoleId;

                    await LoadMenuIdList();
                    await LoadMenuList();

                    _eventAggregator.GetEvent<LoginEvent>().Publish();
                    CloseDialog(new DialogResult(ButtonResult.OK));
                }
                else
                {
                    MessageBox.Show("用户名或密码错误");
                }
            }
            else
            {
                MessageBox.Show("登录失败，请重试");
            }

            IsLogin = false;
        }

        private async Task LoadMenuList()
        {
            var response = await _httpService.GetAsync(Api.MENU_GET_LIST);
            if (response?.code == 1)
            {
                var data = JsonConvert.DeserializeObject<PagingModel<MenuDto>>(JsonConvert.SerializeObject(response.data));
                var menuList = data?.Items.OrderBy(p => p.Sort).ToList();
                AccountInfo.Instance.MenuList = menuList;
            }
        }

        //获取菜单id
        private async Task LoadMenuIdList()
        {
            var response = await _httpService.GetAsync(Api.ROLE_GET_MENULIST);
            if (response?.code == 1)
            {
                var menuIdList = JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(response.data));
                AccountInfo.Instance.MenuIdList = menuIdList ?? [];
            }
        }

        private void ValidateFieldValue(string propertyName, object value)
        {
            var validationContext = new ValidationContext(this) { MemberName = propertyName };
            var results = new List<ValidationResult>();

            if (!Validator.TryValidateProperty(value, validationContext, results))
            {
                var errorMessage = results[0].ErrorMessage ?? "";

                switch (propertyName)
                {
                    case nameof(Username):
                        UsernameError = errorMessage;
                        break;
                    case nameof(Password):
                        PasswordError = errorMessage;
                        break;
                }
            }
            else
            {
                switch (propertyName)
                {
                    case nameof(Username):
                        UsernameError = string.Empty;
                        break;
                    case nameof(Password):
                        PasswordError = string.Empty;
                        break;
                }
            }
        }
    }

}
